// pages/detail/detail.js
const request = require('../../utils/request')
const BASE = 'http://127.0.0.1:8000/static/'

Page({
  data: {
    loading: true,
    drug: {},
    pics: [],
    swiperHeight: 200   // 兜底
  },

  async onLoad(options) {
    try {
      const { data: drug } = await request.get(`/api/v1/drugs/${options.id}`)
      const pics = (drug.pics || []).map(p =>
        p.startsWith('http') ? p : BASE + p
      )
      this.setData({ drug, pics, loading: false })
    } catch (e) {
      wx.showToast({ title: '加载失败', icon: 'none' })
      this.setData({ loading: false })
    }
  },

  // 图片 load 后计算高度
  imgLoaded(e) {
    const { width, height } = e.detail
    if (!width || !height) return           // 容错

    // ① 推荐写法：兼容低版本 + 无警告
    let winWidth
    if (wx.getWindowInfo) {
      winWidth = wx.getWindowInfo().windowWidth     // 基础库 ≥2.24.0
    } else {
      winWidth = wx.getSystemInfoSync().windowWidth // 早期版本兜底
    }

    const swiperHeight = winWidth / (width / height)

    if (this.data.swiperHeight !== swiperHeight) {
      this.setData({ swiperHeight })
    }
  }
})